/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.juhe.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.juhe.admin.config.JuheProperties;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelAttrMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelAttrValueMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGameChannelMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheOrderInfoMapper;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelAttr;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelAttrValue;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelInfo;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelInfoMapper;
import com.pig4cloud.pig.juhe.admin.service.JuheChannelInfoService;
import com.pig4cloud.pig.juhe.api.entity.JuheGameChannel;
import com.pig4cloud.pig.juhe.api.entity.JuheOrderInfo;
import com.pig4cloud.pig.juhe.api.request.ChannelAttrRequest;
import com.pig4cloud.pig.juhe.api.request.JuheChannelRequest;
import com.pig4cloud.pig.juhe.api.util.PythonUtil;
import com.pig4cloud.pig.juhe.api.vo.ChannelConfig;
import com.pig4cloud.pig.juhe.api.vo.JuheChannelAttrVo;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 聚合渠道商表
 *
 * @author yuwenfeng
 * @date 2021-09-02 13:56:17
 */
@Service
@AllArgsConstructor
public class JuheChannelInfoServiceImpl extends ServiceImpl<JuheChannelInfoMapper, JuheChannelInfo> implements JuheChannelInfoService {

	private final JuheChannelAttrMapper juheChannelAttrMapper;
	private final JuheOrderInfoMapper juheOrderInfoMapper;
	private final JuheGameChannelMapper juheGameChannelMapper;
	private final JuheChannelAttrValueMapper juheChannelAttrValueMapper;
	private final JuheProperties juheProperties;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R addChannelInfo(JuheChannelRequest juheChannelInfo) {
		long num = baseMapper.selectCount(new QueryWrapper<JuheChannelInfo>().eq("channel_name", juheChannelInfo.getChannelName()));
		if (num > 0) {
			return R.failed("该渠道名称已存在");
		}
		JuheChannelInfo info = JSON.parseObject(JSON.toJSONString(juheChannelInfo), JuheChannelInfo.class);
		int statusNum = baseMapper.insert(info);
		if (statusNum > 0) {
			if (CollectionUtils.isNotEmpty(juheChannelInfo.getAttrList())) {
				JuheChannelAttr attr = null;
				for (ChannelAttrRequest attrRequest : juheChannelInfo.getAttrList()) {
					int keyNum = juheChannelAttrMapper.selectCount(new QueryWrapper<JuheChannelAttr>().eq("channel_id", info.getChannelId()).eq("attr_key", attrRequest.getAttrKey()));
					if (keyNum > 0) {
						throw new BusinessException(1000, "该渠道的属性KEY：" + attrRequest.getAttrKey() + "已存在，无法添加");
					}
					attr = new JuheChannelAttr();
					attr.setChannelId(info.getChannelId());
					attr.setAttrKey(attrRequest.getAttrKey());
					attr.setAttrName(attrRequest.getAttrName());
					attr.setAttrRequired(attrRequest.getAttrRequired());
					juheChannelAttrMapper.insert(attr);
				}
			}
			return R.ok();
		} else {
			return R.failed("新增操作异常");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R editChannelInfo(JuheChannelRequest juheChannelInfo) {
		List<JuheChannelInfo> list = baseMapper.selectList(new QueryWrapper<JuheChannelInfo>().eq("channel_name", juheChannelInfo.getChannelName()));
		if (CollectionUtils.isNotEmpty(list)) {
			for (JuheChannelInfo info : list) {
				if (!juheChannelInfo.getChannelId().equals(info.getChannelId())) {
					return R.failed("渠道名称已存在");
				}
			}
		}
		JuheChannelInfo info = JSON.parseObject(JSON.toJSONString(juheChannelInfo), JuheChannelInfo.class);
		if (CollectionUtils.isNotEmpty(juheChannelInfo.getAttrList())) {
			JuheChannelAttr attr = null;
			for (ChannelAttrRequest attrRequest : juheChannelInfo.getAttrList()) {
				if (null != attrRequest.getAttrId() && attrRequest.getAttrId() > 0) {//编辑
					List<JuheChannelAttr> attrList = juheChannelAttrMapper.selectList(new QueryWrapper<JuheChannelAttr>().eq("channel_id", info.getChannelId()).eq("attr_key", attrRequest.getAttrKey()));
					if (CollectionUtils.isNotEmpty(attrList)) {
						for (JuheChannelAttr attrCheck : attrList) {
							if (!attrRequest.getAttrId().equals(attrCheck.getAttrId())) {
								throw new BusinessException(1000, "该渠道的属性KEY：" + attrRequest.getAttrKey() + "已存在，无法添加");
							}
						}
					}
					JuheChannelAttr attrInfo = juheChannelAttrMapper.selectById(attrRequest.getAttrId());
					if (null == attrInfo) {
						throw new BusinessException(1000, "属性ID不存在");
					}
					attrInfo.setAttrKey(attrRequest.getAttrKey());
					attrInfo.setAttrName(attrRequest.getAttrName());
					attrInfo.setAttrRequired(attrRequest.getAttrRequired());
					juheChannelAttrMapper.updateById(attrInfo);
				} else {//新增
					int keyNum = juheChannelAttrMapper.selectCount(new QueryWrapper<JuheChannelAttr>().eq("channel_id", info.getChannelId()).eq("attr_key", attrRequest.getAttrKey()));
					if (keyNum > 0) {
						throw new BusinessException(1000, "该渠道的属性KEY：" + attrRequest.getAttrKey() + "已存在，无法添加");
					}
					attr = new JuheChannelAttr();
					attr.setChannelId(info.getChannelId());
					attr.setAttrKey(attrRequest.getAttrKey());
					attr.setAttrName(attrRequest.getAttrName());
					attr.setAttrRequired(attrRequest.getAttrRequired());
					juheChannelAttrMapper.insert(attr);
				}
			}
		}
		int statusNum = baseMapper.updateById(info);
		if (statusNum > 0) {
			return R.ok();
		} else {
			return R.failed("更新操作异常");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R removeChannelById(Long channelId) {
		JuheChannelInfo info = baseMapper.selectById(channelId);
		if (null == info) {
			return R.failed("渠道不存在");
		}
		//删除渠道相关数据
		juheGameChannelMapper.delete(new QueryWrapper<JuheGameChannel>().eq("channel_id", info.getChannelId()));
		juheChannelAttrMapper.delete(new QueryWrapper<JuheChannelAttr>().eq("channel_id", info.getChannelId()));
		juheChannelAttrValueMapper.delete(new QueryWrapper<JuheChannelAttrValue>().eq("channel_id", info.getChannelId()));
		juheOrderInfoMapper.delete(new QueryWrapper<JuheOrderInfo>().eq("channel_id", info.getChannelId()));
		int statusNum = baseMapper.deleteById(info.getChannelId());
		if (statusNum > 0) {
			return R.ok();
		} else {
			return R.failed("删除操作异常");
		}
	}

	@Override
	public R<JuheChannelAttrVo> getChannelAttrVoById(Long channelId) {
		JuheChannelInfo info = baseMapper.selectById(channelId);
		if (null == info) {
			return R.failed("渠道不存在");
		}
		JuheChannelAttrVo vo = JSON.parseObject(JSON.toJSONString(info), JuheChannelAttrVo.class);
		List<JuheChannelAttr> attrList = juheChannelAttrMapper.selectList(new QueryWrapper<JuheChannelAttr>().eq("channel_id", info.getChannelId()).orderByAsc("create_time"));
		if (CollectionUtils.isNotEmpty(attrList)) {
			vo.setAttrList(attrList);
		}
		return R.ok(vo);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R getPythonConfig() throws DocumentException, IOException {
		List<ChannelConfig> configList = PythonUtil.getPythonConfig(juheProperties.getChannelConfigPath());
		if (CollectionUtils.isNotEmpty(configList)) {
			for (ChannelConfig config : configList) {
				JuheChannelInfo info = baseMapper.selectOne(new QueryWrapper<JuheChannelInfo>().eq("channel_name", config.getName()));
				if (null != info) {
					info.setChannelSdkName(config.getCname());
					info.setChannelVersion(config.getSdkversion());
					baseMapper.updateById(info);
					generateAttr(config.getName(), info.getChannelId());
				} else {
					info = new JuheChannelInfo();
					info.setChannelName(config.getName());
					info.setChannelSdkName(config.getCname());
					info.setChannelVersion(config.getSdkversion());
					baseMapper.insert(info);
					generateAttr(config.getName(), info.getChannelId());
				}
			}
		}
		return R.ok();
	}

	/**
	 * @description: 根据配置信息增加属性
	 * @author yuwenfeng
	 * @date 2021/9/15 18:29
	 */
	@Transactional(rollbackFor = Exception.class)
	void generateAttr(String channelName, Long channelId) throws IOException {
		String str = PythonUtil.readTxtFile(juheProperties.getChannelConfigFile() + channelName + ".txt");
		if (StringUtils.isNotBlank(str)) {
			JSONObject jsonData = JSON.parseObject(str);
			JuheChannelAttr attr = null;
			for (Map.Entry<String, Object> entry : jsonData.entrySet()) {
				String attrKey = entry.getKey().toString();
				int attrNum = juheChannelAttrMapper.selectCount(new QueryWrapper<JuheChannelAttr>().eq("attr_key", attrKey).eq("channel_id", channelId));
				if (0 == attrNum) {
					attr = new JuheChannelAttr();
					attr.setChannelId(channelId);
					attr.setAttrKey(attrKey);
					attr.setAttrName("打包" + attrKey);
					attr.setAttrRequired(1);
					juheChannelAttrMapper.insert(attr);
				}
			}
		}
	}
}
